<?php

/**
 * portal actions.
 *
 * @package    ems1
 * @subpackage portal
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class portalActions extends sfActions
{
    public function executeList(sfWebRequest $request)
    {
        $user = $this->getUser()->getGuardUser();
        if($user->hasGroup('Administradores')){
            $this->portals = Doctrine::getTable('EmsPortal')->getAllPortalsOrderByOrganization();
        } else {
            $this->portals = $user->getHasAccessTo();
        }
    }

    public function executeEditor(sfWebRequest $request)
    {
        $this->ems_portal = Doctrine::getTable('EmsPortal')->find(array($request->getParameter('id')));
        $this->forward404Unless($this->ems_portal);
    }

 
    public function executeShow(sfWebRequest $request)
    {
        $this->ems_portal = Doctrine::getTable('EmsPortal')->find(array($request->getParameter('id')));
        $this->forward404Unless($this->ems_portal);

        $goto_editor = $request->getParameter('goto_editor', false);

        return $this->renderPartial('portal/show', array ('portal' => $this->ems_portal, 'goto_editor' =>$goto_editor));
    }

    public function executeNew(sfWebRequest $request)
    {
        $form = new EmsPortalForm();

        return $this->renderPartial('portal/new', array('form' => $form));
    }

    public function executeCreate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST));

        $form = new EmsPortalForm();

        $valid = $this->processForm($request, $form);

        if(!$valid){
            return $this->renderPartial('portal/new', array('form' => $form));
        } else {
            return sfView::NONE;
        }
    }

    public function executeEdit(sfWebRequest $request)
    {
        $form = new EmsPortalForm($this->getRoute()->getObject());

        return $this->renderPartial('form', array('form' => $form));
    }

    public function executeUpdate(sfWebRequest $request)
    {
        $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
        $this->forward404Unless($portal = Doctrine::getTable('EmsPortal')->find(array($request->getParameter('id'))),
                sprintf('Object ems_portal does not exist (%s).', $request->getParameter('id'))
            );
        $form = new EmsPortalForm($portal);

        $valid = $this->processForm($request, $form);

        if(!$valid){
            return $this->renderPartial('portal/form', array ('form'=>$form));
        } else {
            return sfView::NONE;
        }
    }

//    public function executeDelete(sfWebRequest $request)
//    {
//        $request->checkCSRFProtection();
//
//        $this->forward404Unless($ems_portal = Doctrine::getTable('EmsPortal')->find(array($request->getParameter('id'))),
//                sprintf('Object ems_portal does not exist (%s).', $request->getParameter('id')));
//        $ems_portal->delete();
//
//        $this->redirect('portal/index');
//    }

    public function executeToogleServiceButtons(sfWebRequest $request)
    {
        $portal = $this->getRoute()->getObject();

        if ($portal->getUsesServButtons()) {
            $portal->setUsesServButtons(false);

            if($portal->hasServiceButtons()){
                foreach ($portal->getServiceButtons() as $button) {
                    $button->setIsEnabled(false);
                    $button->save();
                }
            }
        } else {
            $portal->setUsesServButtons(true);

            if(!$portal->hasServiceButtons()){
                $this->createServiceButtons($portal);
            } else {
                foreach ($portal->getServiceButtons() as $button) {
                    if($button->getType()->getType() !== 'SMS'){
                        $button->setIsEnabled(true);
                        $button->save();
                    }
                }
            }
        }

        $portal->save();

        return $this->renderPartial('portal/updateTree', array('portal' => $portal));
    }

    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        $valid = $form->isValid();
        if ($valid){
            if($form->getObject()->isNew()){
                $portal = $form->save();
                
                $user = $this->getUser()->getGuardUser();

                $access = new EmsHasAccess();

                $access->setPortal($portal);
                $access->setUser($user);

                $access->save();

                $audit = new EmsAudit();

                $audit->setPortal($portal);
                $audit->setUser($user);
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear portal'));
                $audit->setObjectId($portal->getId());

                $audit->save();
                
                $this->createHomeSecction($portal, $user);
                
                $this->createDefaultHeader($portal, $user);

                $this->createDefaultFooter($portal, $user);

                if($portal->getUsesRegister()){
                    $this->createRegisterSecction($portal, $user);
                }

                if($portal->getUsesServButtons()){
                    $this->createServiceButtons($portal, $user);
                }

                return $this->renderPartial('portal/multiupdateNew',array('portals' => $user->getHasAccessTo(),'portal' => $portal));
            } else {
                $portal = $form->save();

                $user = $this->getUser()->getGuardUser();

                $audit = new EmsAudit();

                $audit->setPortal($portal);
                $audit->setUser($user);
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar portal'));
                $audit->setObjectId($portal->getId());

                $audit->save();

                if($portal->getUsesRegister()){
                    if(!$portal->hasRegisterSection()){
                        $this->createRegisterSecction($portal, $user);
                    } else {
                        $register = $portal->getRegisterSection();
                        $register->setIsEnabled(true);
                        $register->save();

                        $audit = new EmsAudit();

                        $audit->setPortal($portal);
                        $audit->setUser($user);
                        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar sección'));
                        $audit->setObjectId($register->getId());

                        $audit->save();
                    }
                } else {
                    if($portal->hasRegisterSection()){
                        $register = $portal->getRegisterSection();
                        $register->setIsEnabled(false);
                        $register->save();

                        $audit = new EmsAudit();

                        $audit->setPortal($portal);
                        $audit->setUser($user);
                        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar sección'));
                        $audit->setObjectId($register->getId());

                        $audit->save();
                    }
                }

                if($portal->getUsesServButtons()){
                    if(!$portal->hasServiceButtons()){
                        $this->createServiceButtons($portal, $user);
                    } else {
                        foreach ($portal->getServiceButtons() as $button) {
                            $button->setIsEnabled(true);
                            $button->save();

                            $audit = new EmsAudit();

                            $audit->setPortal($portal);
                            $audit->setUser($user);
                            $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar boton de servicio'));
                            $audit->setObjectId($button->getId());

                            $audit->save();
                        }
                    }
                } else {
                    if($portal->hasServiceButtons()){
                        foreach ($portal->getServiceButtons() as $button) {
                            $button->setIsEnabled(false);
                            $button->save();

                            $audit = new EmsAudit();

                            $audit->setPortal($portal);
                            $audit->setUser($user);
                            $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar boton de servicio'));
                            $audit->setObjectId($button->getId());

                            $audit->save();
                        }
                    }
                }
                return $this->renderPartial('portal/multiupdateEdit',array('portal' => $portal));
            }  
        }

        return $valid;
    }

    protected function createDirectoriesStructure(EmsPortal $portal)
    {
        mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId());
        mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/images');
        mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/sounds');
        mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/videos');
        mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/temp_files');
        mkdir(sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/css');
    }

    protected function createHomeSecction(EmsPortal $portal, sfGuardUser $user)
    {
        $section = new EmsSection();
        $section->setTitle('Inicio');
        $section->setSlug(Slug::slugify('Inicio'));
        $section->setIsSubsection(false);
        $section->setType(Doctrine::getTable('EmsSectionType')->findOneBy('type', 'Home'));
        $section->setMaxContentsPerPage(0);
        $section->setPortal($portal);

        $section->save();

        $audit = new EmsAudit();

        $audit->setPortal($portal);
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear sección'));
        $audit->setObjectId($section->getId());

        $audit->save();
    }

    protected function createRegisterSecction(EmsPortal $portal, sfGuardUser $user)
    {
        $section = new EmsSection();
        $section->setTitle('Registro');
        $section->setSlug(Slug::slugify('Registro'));
        $section->setIsEnabled(true);
        $section->setIsSubsection(false);
        $section->setType(Doctrine::getTable('EmsSectionType')->findOneBy('type', 'Register'));
        $section->setMaxContentsPerPage(0);
        $section->setPortal($portal);

        $section->save();

        $audit = new EmsAudit();

        $audit->setPortal($portal);
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear sección'));
        $audit->setObjectId($section->getId());

        $audit->save();

        $this->createDefaultRegisterForm($section, $user);
    }

    protected function createDefaultRegisterForm(EmsSection $section, sfGuardUser $user)
    {
        $element = new EmsElement();
        $element->setType(Doctrine::getTable('EmsElementType')->findOneBy('type', 'Form'));
        $element->setTitle('Datos de registro');
        $element->setPosition(1);

        $element->setForm(new EmsForm());

        $element->setSection($section);

        $element->save();

        $audit = new EmsAudit();

        $audit->setPortal($section->getPortal());
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear elemento'));
        $audit->setObjectId($element->getId());

        $audit->save();
        
        $this->createDefaultRegisterFormFields($element->getForm());
    }

    protected function createDefaultRegisterFormFields(EmsForm $form) {
        $nameField = new EmsFormField();
        $lastnameField = new EmsFormField();
        $idField = new EmsFormField();
        $emailField = new EmsFormField();

        $nameField->setForm($form);
        $lastnameField->setForm($form);
        $idField->setForm($form);
        $emailField->setForm($form);

        $nameField->setFieldType(Doctrine::getTable('EmsFieldType')->findOneBy('type', 'shorttext'));
        $lastnameField->setFieldType(Doctrine::getTable('EmsFieldType')->findOneBy('type', 'shorttext'));
        $idField->setFieldType(Doctrine::getTable('EmsFieldType')->findOneBy('type', 'idnumber'));
        $emailField->setFieldType(Doctrine::getTable('EmsFieldType')->findOneBy('type', 'email'));

        $nameField->setTitle('Nombre');
        $lastnameField->setTitle('Apellido');
        $idField->setTitle('Cedula');
        $emailField->setTitle('Correo Electrónico');

        $idField->setIsKey(true);
        $idField->setIsUnique(true);

        $emailField->setIsUnique(true);

        $nameField->setIsRequired(true);
        $lastnameField->setIsRequired(true);
        $idField->setIsRequired(true);
        $emailField->setIsRequired(true);

        $nameField->save();
        $lastnameField->save();
        $idField->save();
        $emailField->save();
    }

    protected function createServiceButtons(EmsPortal $portal, sfGuardUser $user)
    {
        foreach (Doctrine::getTable('EmsServiceType')->findAll() as $type) {
            $button = new EmsServiceButton();

            $button->setType($type);
            $button->setPortal($portal);

            switch ($type->getType()) {
                case 'Twitter':
                    $button->setMessage('%cont%: %c-url% en el sitio %portal%: %p-url%');
                    break;
                case 'Email':
                    $button->setMessage('<p>Hola,</p><p>Ha recibido un contenido desde el sitio <a href="%p-url%"><b>%portal%</b></a></p>
                        <p>Haga clic <a href="%c-url%">aquí</a> para ir al contenido: <a href="%c-url%"><b>%cont%</b></a></p>');
                    break;
                default:
                    $button->setMessage('Visite '.$portal->getTitle().' (http://'.sfConfig::get('app_hostname').'/'.$portal->getSlug().')');
                    break;
            }
            
            $button->setThumbSmall(strtolower($type->getType()).'_small.jpg');
            $button->setThumbBig(strtolower($type->getType()).'_big.jpg');

            copy(sfConfig::get('sf_upload_dir').'/default/'.$button->getThumbSmall(),
                    sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/images/'.$button->getThumbSmall());
            copy(sfConfig::get('sf_upload_dir').'/default/'.$button->getThumbBig(),
                    sfConfig::get('sf_upload_dir').'/portal_'.$portal->getId().'/images/'.$button->getThumbBig());

            if($type->getType() == 'SMS'){
                $button->setIsEnabled(false);
                $button->setPublished(false);
            }

            $button->save();

            $audit = new EmsAudit();

            $audit->setPortal($portal);
            $audit->setUser($user);
            $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear boton de servicio'));
            $audit->setObjectId($button->getId());

            $audit->save();
        }
    }

    protected function createDefaultHeader(EmsPortal $portal, sfGuardUser $user)
    {
        $elementBanner = new EmsElement();
        $elementBanner->setType(Doctrine::getTable('EmsElementType')->findOneByType('Banner'));

        $banner = new EmsBanner();

        foreach (Doctrine::getTable('EmsBannerSize')->findAll() as $size) {
            $image = new EmsBannerImage();
            $image->setSize($size);
            $banner->getImages()->add($image);
        }

        $elementBanner->setBanner($banner);
        $elementBanner->setTitle('Imagen');
        $elementBanner->setPosition(1);

        $elementMenu = new EmsElement();
        $elementMenu->setType(Doctrine::getTable('EmsElementType')->findOneByType('Menu'));
        $elementMenu->setPosition(2);

        $menu = new EmsMenu();

        $option = new EmsMenuOption();

        $option->setIsLocal(true);
        $option->setSection($portal->getHomeSection());
        $option->setLink('');
        $option->setTitle('');
        
        $menu->getOptions()->add($option);
        $menu->setRenderTitle(false);
        $menu->setIsVertical(false);

        $elementMenu->setMenu($menu);
        $elementMenu->setTitle('Menú Principal');

        $header = new EmsHeader();

        $header->getElements()->add($elementBanner);
        $header->getElements()->add($elementMenu);

        $header->setPortal($portal);
        $header->save();

        $audit = new EmsAudit();

        $audit->setPortal($portal);
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear header'));
        $audit->setObjectId($header->getId());

        $audit->save();

        $auditBanner = new EmsAudit();

        $auditBanner->setPortal($portal);
        $auditBanner->setUser($user);
        $auditBanner->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear elemento'));
        $auditBanner->setObjectId($elementBanner->getId());

        $audit->save();

        $auditMenu = new EmsAudit();

        $auditMenu->setPortal($portal);
        $auditMenu->setUser($user);
        $auditMenu->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear elemento'));
        $auditMenu->setObjectId($elementMenu->getId());

        $auditMenu->save();
    }

    protected function createDefaultFooter(EmsPortal $portal, sfGuardUser $user)
    {
        $elementBanner = new EmsElement();
        $elementBanner->setType(Doctrine::getTable('EmsElementType')->findOneByType('Banner'));

        $banner = new EmsBanner();

        foreach (Doctrine::getTable('EmsBannerSize')->findAll() as $size) {
            $image = new EmsBannerImage();
            $image->setSize($size);

            $banner->getImages()->add($image);
        }

        $elementBanner->setBanner($banner);
        $elementBanner->setTitle('Imagen');
        $elementBanner->setPosition(1);

        $footer = new EmsFooter();

        $footer->getElements()->add($elementBanner);
        $footer->setHtml('<p>Aquí va el Footer.</p>');

        $footer->setPortal($portal);
        $footer->save();

        $audit = new EmsAudit();

        $audit->setPortal($portal);
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear footer'));
        $audit->setObjectId($footer->getId());

        $audit->save();

        $auditBanner = new EmsAudit();

        $auditBanner->setPortal($portal);
        $auditBanner->setUser($user);
        $auditBanner->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear elemento'));
        $auditBanner->setObjectId($elementBanner->getId());

        $audit->save();
    }

    public function executeHeaderShow(sfWebRequest $request)
    {
        $header = $this->getRoute()->getObject();

        return $this->renderPartial('showHeader', array('header' => $header));
    }

    public function executeHeaderEditBanner(sfWebRequest $request)
    {
        $header = $this->getRoute()->getObject();

        if($header->getUsesBanner()){
                $header->setUsesBanner(false);
                $header->save();
        } else {
            $header->setUsesBanner(true);
            $header->save();
        }

        $user = $this->getUser()->getGuardUser();

        $audit = new EmsAudit();

        $audit->setPortal($header->getPortal());
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar header'));
        $audit->setObjectId($header->getId());

        $audit->save();

        return $this->renderPartial('showHeader', array('header' => $header));
    }

    public function executeHeaderEditMenu(sfWebRequest $request)
    {
        $header = $this->getRoute()->getObject();

        if($header->getUsesMenu()){
                $header->setUsesMenu(false);
                $header->save();
        } else {
            $header->setUsesMenu(true);
            $header->save();
        }

        $user = $this->getUser()->getGuardUser();

        $audit = new EmsAudit();

        $audit->setPortal($header->getPortal());
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar header'));
        $audit->setObjectId($header->getId());

        $audit->save();

        return $this->renderPartial('showHeader', array('header' => $header));
    }

    public function executeFooterShow(sfWebRequest $request)
    {
        $footer = $this->getRoute()->getObject();

        return $this->renderPartial('showFooter', array('footer' => $footer));
    }

    public function executeFooterUpdate(sfWebRequest $request)
    {
        $footer = $this->getRoute()->getObject();

        $form = new EmsFooterForm($footer);

        if($request->isMethod(sfRequest::POST)){
            return $this->renderPartial('editFooter', array('form' => $form));
        } elseif ($request->isMethod(sfRequest::PUT)) {
            if(!$this->processFooterForm($request, $form)){
                return $this->renderPartial('editFooter', array('form' => $form));
            } else {
                return sfView::NONE;
            }
        }
    }

    protected function processFooterForm(sfWebRequest $request, EmsFooterForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        $valid = $form->isValid();
        if ($valid)
        {
            $audit = new EmsAudit();

            if($form->getObject()->isNew()){
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Crear footer'));
            } else {
                $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar footer'));
            }
            
            $footer = $form->save();

            $user = $this->getUser()->getGuardUser();

            $audit->setPortal($footer->getPortal());
            $audit->setUser($user);
            $audit->setObjectId($footer->getId());

            $audit->save();

            return $this->renderPartial('showFooter', array('footer' => $footer));
        }

        return $valid;
    }
    
    public function executeFooterEditBanner(sfWebRequest $request)
    {
        $footer = $this->getRoute()->getObject();

        if($footer->getUsesBanner()){
            $footer->setUsesBanner(false);
            $footer->save();
        } else {
            $footer->setUsesBanner(true);
            $footer->save();
        }

        $audit = new EmsAudit();

        $user = $this->getUser()->getGuardUser();

        $audit->setPortal($footer->getPortal());
        $audit->setUser($user);
        $audit->setAction(Doctrine::getTable('sfGuardPermission')->findOneByName('Editar footer'));
        $audit->setObjectId($footer->getId());

        $audit->save();

        return $this->renderPartial('showFooter', array('footer' => $footer));
    }

    public function  executeListComments(sfWebRequest $request)
    {
        $portal = $this->getRoute()->getObject();

        $pager = new sfDoctrinePager('EmsPortal', 10);
        $pager->setQuery($portal->getEnabledCommentsQuery());
        $pager->setPage($request->getParameter('page', 1));
        $pager->init();

        $form = new CommenstForApprovalContainerForm($pager->getResults());
        
        if ($request->isMethod(sfRequest::PUT)) {
            if($this->processCommentsApproval($request, $form)){
                $page = $request->getParameter('page', 1);

                $next = $request->getParameter('next', 1);

                if($page == $next){
                    $pager->setPage($pager->getFirstPage());
                } else {
                    $pager->setPage($next);
                }

                $pager->init();

                $form = new CommenstForApprovalContainerForm($pager->getResults());
            }
        }
        return $this->renderPartial('commentList', array('portal' => $portal,'pager' => $pager, 'form' => $form));
    }

    protected function processCommentsApproval(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()));

        $valid = $form->isValid();

        if ($valid){
            $form->save();
        }

        return $valid;
    }

    public function executeTempFileUpload(sfWebRequest $request){

        $portal_id = $request->getParameter('portal_id',false);

        $form = new EmsPortalForm();

        $files = $request->getFiles($form->getName());

        $json_response = array();

        $file = null;

        $errors = array();

        $file = $files['tmp_image'];

        $validator = new jsValidatorImage(array(
                            'mime_types' => array('image/jpeg'),
                            'trim'       => true,
                            'path'       => sfConfig::get('sf_upload_dir').($portal_id ? '/portal_'.$portal_id.'/temp_files/':'/temp_files/'),
                            'required'   => true,
                            'max_size'   => '1048576',
                            'minx'       => 100,
                            'maxx'       => 100,
                            'miny'       => 100,
                            'maxy'       => 100
                        ), array(
                            'required'   => 'Debe indicar el archivo de formato .JPEG a ser cargado.',
                            'max_size'   => 'La imagen excede el peso máximo de archivo permitido, 1 MB.',
                            'mime_types' => 'Tipo de archivo invalido (%mime_type%), el archivo a cargar debe ser de tipo JPEG'
                        ));

        try {

            $validator->clean($file);

        } catch (sfValidatorError $e) {

            $json_response['valid'] = false;

            $json_response['error_message'] = $e->getMessage();

            return $this->renderText(json_encode($json_response));
        }

        $json_response['valid'] = true;

        $json_response['file_name'] = $file['name'];

        $json_response['temp_file'] = Util::saveTempFile($file, $portal_id);

        $json_response['size'] = $file['size'];

        $json_response['type'] = $file['type'];

        return $this->renderText(json_encode($json_response));
    }
}
